#include "unique_label_qlist_widget.h"


UniqueLabelQListWidget::UniqueLabelQListWidget(QWidget *parent)
    : EscapableQListWidget(parent) {}

void UniqueLabelQListWidget::mousePressEvent(QMouseEvent *event)
{
    EscapableQListWidget::mousePressEvent(event);
    if (!this->indexAt(event->pos()).isValid())
    {
        this->clearSelection();
    }
}

QListWidgetItem *UniqueLabelQListWidget::findItemByLabel(const QString &label)
{
    for (int row = 0; row < this->count(); ++row)
    {
        QListWidgetItem *item = this->item(row);
        if (item->data(Qt::UserRole).toString() == label)
        {
            return item;
        }
    }
    return nullptr;
}

QListWidgetItem *UniqueLabelQListWidget::createItemFromLabel(const QString &label)
{
    if (findItemByLabel(label))
    {
        throw std::runtime_error(QString("Item for label '%1' already exists").arg(label).toStdString());
    }

    QListWidgetItem *item = new QListWidgetItem();
    item->setData(Qt::UserRole, label);
    return item;
}

void UniqueLabelQListWidget::setItemLabel(QListWidgetItem *item, const QString &label, const QColor &color)
{
    QLabel *qlabel = new QLabel();
    if (!color.isValid())
    {
        qlabel->setText(label);
    }
    else
    {
        QString colorStr = QString("#%1%2%3")
        .arg(color.red(), 2, 16, QChar('0'))
            .arg(color.green(), 2, 16, QChar('0'))
            .arg(color.blue(), 2, 16, QChar('0'));

        QString text = QString("%1 <font color=\"%2\">●</font>")
                           .arg(label.toHtmlEscaped(), colorStr);
        qlabel->setText(text);
    }
    qlabel->setAlignment(Qt::AlignBottom);

    item->setSizeHint(qlabel->sizeHint());

    this->setItemWidget(item, qlabel);
}
